<template>
  <yy-page custom-class="pageWhiteBg">
    <view class="login-page">
      <!-- #ifdef H5 -->
      <login-h5 :logo="logo" v-if="showMobileLogin" @loginCb="registerSuccess" @ganTestUserInfo="ganTestUserInfo"></login-h5>
      <!-- #endif -->
      <zm-image :src="logo" custom-style="width:152rpx;height:118rpx;margin:300rpx auto 0" v-if="!showMobileLogin"></zm-image>
      <view>
        <view class="flex-col flex-c-m wx-content" v-if="!showMobileLogin">
          <view class="fc8 fs26 mb30">申请获取你的手机号和公开信息（昵称、头像等）</view>
          <u-modal
            :show="showPhoneBtn"
            :zoom="false"
            width="540rpx"
            negative-top="150"
            title="授权绑定手机号"
            :show-cancel-button="true"
            content="为了更好的为您提供服务，需要 授权获取您的手机号进行绑定。"
          >
            <view slot="confirmButton" class="flex">
              <view class="flex-1 flex-c-m fs32 u-model-btn-solid" @click="showPhoneBtn = false">取消</view>
              <!-- #ifdef MP-ALIPAY -->
              <view class="flex-1 fs32 diy-btn">
                <button
                  open-type="getPhoneNumber"
                  scope="phoneNumber"
                  style="color: #3bc5d2; font-size: 32rpx; border: none; height: 100rpx; line-height: 100rpx"
                  @getphonenumber="handlerGetPhone"
                  >确认绑定</button
                >
              </view>
              <!-- #endif -->
              <!-- #ifdef MP-WEIXIN-->
              <view class="flex-1 fs32 diy-btn">
                <button
                  open-type="getPhoneNumber"
                  style="color: #3bc5d2; font-size: 32rpx; border-style: none; background-color: white; height: 100rpx; line-height: 100rpx"
                  @getphonenumber="handlerGetPhone"
                  @click="showPhoneBtn = false"
                  >确认绑定</button
                >
              </view>
              <!-- #endif -->
              <!-- #ifdef H5 -->
              <view class="flex-1 fs32 diy-btn">
                <button style="color: #3bc5d2; font-size: 32rpx; border-style: none !important; background-color: white; height: 100rpx; line-height: 100rpx" @click="toBindTel"
                  >去绑定</button
                >
              </view>
              <!-- #endif -->
            </view>
          </u-modal>
          <!-- #ifdef MP-WEIXIN || H5 -->
          <yy-button custom-style="height:100rpx" class="login-wx bc-primary" v-if="!hasLogin" open-type="getUserInfo" @click="ganTestUserInfo">快速登录</yy-button>
          <!-- #endif -->
          <!-- #ifdef MP-ALIPAY -->
          <yy-button v-if="!hasLogin" custom-style="height:100rpx" custom-class="login-wx bc-primary" open-type="getUserInfo" @click="aliPayLogin">支付宝快速登录</yy-button>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN -->
          <yy-button v-if="hasLogin" open-type="getPhoneNumber" custom-style="height:100rpx" class="login-wx bc-primary" @getphonenumber="handlerGetPhone">绑定手机号</yy-button>
          <!-- #endif -->
          <!-- #ifdef MP-ALIPAY -->
          <button v-if="hasLogin" open-type="getPhoneNumber" scope="phoneNumber" style="height: 100rpx" class="login-wx bc-primary" @getphonenumber="handlerGetPhone"
            >绑定手机号</button
          >
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <yy-button v-if="hasLogin" custom-style="height:100rpx" class="login-wx bc-primary" @click="toBindTel">绑定手机号</yy-button>
          <!-- #endif -->
          <!-- #ifdef H5 -->
          <view class="login-mobile" @click="handleMobile" v-if="!showPhoneBtn"> 手机号登录 </view>
          <!-- #endif -->
          <!-- #ifdef MP-WEIXIN || MP-ALIPAY -->
          <view class="mb10 mt10" @click="handleNotLogin">
            {{ !hasLogin ? '暂不登录' : '暂不绑定' }}
          </view>
          <!-- #endif -->
        </view>

        <!-- 服务协议 -->
        <view class="login-footer" :class="showMobileLogin ? 'margin270' : 'margin58'" @click="changeFeChecked">
          <yy-check v-if="mustCheck()" :check="checkAgree" :size="22" :shape="'circle'" @change="changeFeChecked"></yy-check>
          <text v-if="mustCheck()" class="fca">已阅读并同意</text>
          <text v-if="!mustCheck()" class="fca">登录代表您已同意</text>
          <text class="fc-primary" @click.stop="userAgree('1')">《用户服务协议》</text>
          <text class="fc-primary" @click.stop="userAgree('2')">《隐私协议》</text>
        </view>
      </view>
    </view>
    <user-agree v-model="show" :title="agreeTitle" :content="toHtml(agreeContent)"></user-agree>
  </yy-page>
</template>

<script>
  import ZmImage from '@/commons/ZmImage/index.vue'
  import UserAgree from '@/components/UserAgree.vue'
  import pageMixins from '@/mixins/pageMixins'

  import * as utils from '@/utils/index'
  import * as auth from '@/utils/auth'
  import { navigateTo } from '@/utils/tools'
  import { locActivityPrize } from '@/utils/locStore/data'
  //#ifdef H5
  import LoginH5 from './loginH5/index.vue'
  import { initWx } from '@/utils/h5/handleEvn'
  //#endif
  export default {
    name: 'login',
    mixins: [pageMixins],
    components: {
      ZmImage,
      UserAgree,
      //#ifdef H5
      LoginH5
      //#endif
    },
    data() {
      return {
        tabList: ['pages/index/index', 'pages/ticket/ticket', 'pages/mall/mall', 'pages/mine/index'],
        showMobileLogin: false, // 是否显示手机号登录
        showPhoneBtn: false,
        canIUseGetUserProfile: false,
        showWxSubscribe: false,
        // 新增变量
        agreeInfo: {
          userAt: '', //用户服务协议
          userPyAt: '' //隐私协议
        }, //用户协议信息
        agreeTitle: '', //用户协议名称
        agreeContent: '', //用户协议内容
        show: false, //用户协议弹窗开关
        redirect: '',
        userMsg: null,
        checkAgree: false
      }
    },
    computed: {
      logo() {
        return this.$auth.getBaseSetLogo()
      },
      hasLogin() {
        return this.$auth.getIslogin()
      }
    },
    created() {
      if (wx.getUserProfile) {
        this.canIUseGetUserProfile = true
      }
    },
    onLoad(option) {
      if (option) {
        this.showPhoneBtn = !!option.bindMobile
        if (this.showPhoneBtn) {
          this.showMobileLogin = false
        }
      }
      this.redirect = option.redirect ? decodeURIComponent(option.redirect) : ''
    },
    onShow() {
      console.log(this.$tools.getCurrentPage())
      this.init()
    },
    methods: {
      async init() {
        auth.toGetToken().then((token) => {
          this.getAgreement()
          // #ifdef H5
          if (this.$tools.isWxBrowswer()) {
            this.isBindMobile()
          }
          // #endif
        })
      },
      registerSuccess() {
        uni.$api.activity
          .getRegisterActivityPrize()
          .then((res) => {
            console.log('registerSuccess', res, res && res.length > 0)
            if (res && res.length > 0) {
              console.log('registerSuccess res')
              locActivityPrize.set(res)
              navigateTo('/pages/mine/index', {}, 'reLaunch')
            } else {
              console.log('registerSuccess loginCb')
              this.loginCb()
            }
          })
          .catch((e) => {
            console.log('registerSuccess catch', e)
            this.loginCb()
          })
      },
      loginCb(res) {
        res && auth.saveUserInfo(res)
        this.setIsReload()

        console.log(this.$tools.getCurrentPage())
        const router = this.$tools.getCurrentPage()
        let fromPath = null

        fromPath = router.fromPath

        console.log(router, fromPath)
        console.log(fromPath, '授权回调的上一个页面')

        this.$nextTick(() => {
          if (this.redirect) {
            console.log(this.redirect, fromPath)
            const type = this.tabList.includes(fromPath) ? 'switchTab' : 'redirectTo'
            navigateTo(this.redirect, {}, type)
          } else {
            if (this.tabList.includes(fromPath)) {
              // 判断是否是主页下tab页
              this.$tools.navigateTo('/' + fromPath, {}, 'switchTab')
            } else {
              if (!fromPath || fromPath === 'pages/login/index') {
                // 防止意外：前一页为空或者还是登录页的情况
                // #ifndef MP-TOUTIAO
                navigateTo('/pages/index/index', {}, 'reLaunch')
                // #endif
                // #ifdef MP-TOUTIAO
                navigateTo('/pages/ticket/ticket', {}, 'reLaunch')
                // #endif
              } else {
                if (fromPath === 'pagesOrder/filmCouponByTT/index') {
                  navigateTo('/pagesOrder/filmCouponByTT/index', {}, 'reLaunch')
                } else {
                  this.$tools.navigateTo(-1)
                }
              }
            }
          }
        })
      },
      handleNotLogin() {
        this.$nextTick(() => {
          navigateTo('/pages/index/index', this.redirect, 'reLaunch')
        })
      },
      wxloginCb(res) {
        res && auth.saveUserInfo(res)
      },

      closePopup() {
        this.showPhoneBtn = false
      },
      closeSubscribe() {
        this.showWxSubscribe = false
      },
      // toServiceAgreement() {
      //   navigateTo('/pages/serviceAgreement/index')
      // },
      getAgreement() {
        uni.$api.channel.getAgreement({ agreementList: 'userAt,userPyAt' }).then((res) => {
          console.log(res)
          this.agreeInfo = res || {}
        })
      },
      // 用户协议
      userAgree(type) {
        if (type === '1') {
          this.agreeTitle = '用户服务协议'
          this.agreeContent = this.agreeInfo.userAt || ''
        } else if (type === '2') {
          this.agreeTitle = '隐私协议'
          this.agreeContent = this.agreeInfo.userPyAt || ''
        }

        this.show = true
      },
      handlerGetPhone(e) {
        // #ifdef MP-WEIXIN
        console.log(new Date(), e, '开始')
        // 授权手机号
        this.showPhoneBtn = false
        console.log(new Date(), e.detail, e, '开始')
        this.handlerAfterGetPhone(e.detail)
        // #endif
        // #ifdef MP-ALIPAY
        this.showPhoneBtn = false
        try {
          // const data = await my.getAuthCode({ scopes: 'auth_user' })
          // const data = await my.getAuthCode({ scopes: 'auth_user' })
          // console.log('data', data)
          my.getPhoneNumber({
            success: (res) => {
              console.log('data', res)
              this.doBindPhone(res.response)
            }
          })
        } catch (err) {
          console.log('onGetAuthorize ERR: ', err)
        }
        // #endif
      },
      async handlerAfterGetPhone(phoneEventDetail) {
        // 授权回调-手机号
        const { errMsg } = phoneEventDetail
        if (errMsg === 'getPhoneNumber:ok') {
          this.code = await this.$auth.miniCode()
          this.doBindPhone(phoneEventDetail, this.code)
        }
      },

      ganTestUserInfo() {
        // #ifdef MP-WEIXIN
        if (!this.checkAgree) {
          this.$msg.toast('请阅读并勾选底部《用户服务协议》《隐私协议》')
          return
        }
        // 用户授权
        uni.getUserProfile({
          desc: '用于完善会员资料',
          success: async (res) => {
            this.showMobileLogin = false
            this.code = await this.$auth.miniCode()
            this.doLogin(res, this.code)
          },
          fail: (err) => {
            console.log('err', err)
          }
        })
        // #endif
        // #ifdef H5
        console.log('初始化initWx-------------------------------------------------')
        initWx('toAuth')
        // #endif
      },
      async aliPayLogin(info) {
        if (!this.checkAgree) {
          this.$msg.toast('请阅读并勾选底部《用户服务协议》《隐私协议》')
          return
        }
        console.log('aliPayLogin', info)
        try {
          // const userInfo = await my.getAuthCode()
          // eslint-disable-next-line no-undef
          const data = await my.getAuthCode({ scopes: 'auth_user' })
          // console.log('userInfo: ', userInfo)
          // userInfo = JSON.parse(userInfo.response).response
          console.log('data: ', data)
          this.doLogin(data, 0)
        } catch (err) {
          console.log('onGetAuthorize ERR: ', err)
        }
      },
      doLogin(allInfo = { iv: '', encryptedData: null, userInfo: {} }, code) {
        let params = {}
        // #ifdef MP-TOUTIAO
        params = {
          type: 'douyin',
          data: JSON.stringify({
            code: code,
            payload: {
              iv: allInfo && allInfo.iv,
              encryptedData: allInfo.encryptedData
            }
          })
        }
        // #endif
        // #ifdef MP-WEIXIN
        params = {
          type: 'weixin',
          data: JSON.stringify({
            code: code,
            payload: {
              iv: allInfo && allInfo.iv,
              encryptedData: allInfo.encryptedData
            }
          })
        }
        // #endif
        // #ifdef MP-ALIPAY
        params = {
          type: 'ali',
          loginType: 'unionId',
          data: JSON.stringify({
            code: allInfo.authCode
          })
        }
        // #endif
        this.$msg.loading()
        uni.$api.public
          .loginByOAuth2(params)
          .then(async () => {
            auth
              .toGetUserInfo(true)
              .then(async (res) => {
                this.$msg.hideLoading()
                // this.hasLogin = true
                // #ifdef MP-WEIXIN
                this.code = await this.$auth.miniCode()
                // #endif
                console.log('绑定手机号', res.bindingMobile)
                if (res.bindingMobile) {
                  // 已经绑定过手机号码
                  this.showPhoneBtn = false
                  this.loginCb(res)
                } else {
                  // 未绑定手机号码
                  this.wxloginCb(res)
                  this.showPhoneBtn = true
                }
              })
              .catch(() => {
                this.$msg.hideLoading()
              })
          })
          .catch(() => {
            this.$msg.hideLoading()
          })
      },
      doBindPhone(phoneEventDetail = { iv: '', encryptedData: null, code: '' }, code) {
        let params = {}
        // #ifdef MP-WEIXIN
        params = {
          data: JSON.stringify({
            code,
            payload: {
              iv: phoneEventDetail && phoneEventDetail.iv,
              encryptedData: phoneEventDetail.encryptedData
            }
            // needLoading: true
          })
        }
        this.$msg.loading()
        uni.$api.public
          .bindMobileByWeiXin(params)
          .then(async () => {
            this.$msg.hideLoading()
            //缺少获取用户信息相关
            this.registerSuccess()
          })
          .catch((e) => {
            console.log('bindMobileByWeiXin catch', e)
          })
        // #endif

        // #ifdef MP-ALIPAY
        console.log('phoneEventDetail', JSON.parse(phoneEventDetail))
        params = {
          type: 'ali',
          loginType: 'mobile',
          data: JSON.stringify({
            code: JSON.parse(phoneEventDetail).response
          })
        }
        this.$msg.loading()
        uni.$api.public
          .bindMobileByAli(params)
          .then(async () => {
            console.log('bindMobileByAli')
            this.$msg.hideLoading()
            //缺少获取用户信息相关
            this.registerSuccess()
          })
          .catch(() => {
            this.$msg.hideLoading()
          })
        // #endif
      },

      toHtml(content) {
        return utils.toHtml(content)
      },
      handleMobile() {
        this.showMobileLogin = true
      },
      mustCheck() {
        return this.$auth.platform() === 'mp-alipay' || this.$auth.platform() === 'mp-weixin'
      },
      changeFeChecked() {
        this.checkAgree = !this.checkAgree
      },
      // #ifdef H5
      isBindMobile() {
        auth
          .toGetUserInfo(true, 'auth')
          .then(async (res) => {
            // this.hasLogin = true
            console.log(res)
            console.log('绑定手机号', res.bindingMobile)

            if (res.bindingMobile) {
              // 已经绑定过手机号码
              this.showPhoneBtn = false
              this.registerSuccess()
              // this.loginCb(res)
            } else {
              // 未绑定手机号码
              this.wxloginCb(res)
              this.showPhoneBtn = true
            }
          })
          .catch((err) => {
            console.log(err, '拒绝了授权')
          })
      },
      toBindTel() {
        this.showPhoneBtn = false
        this.$tools.navigateTo('/subPages/bindMobile/index')
      }
      // #endif
    }
  }
</script>

<style lang="scss">
  .login-page {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: 100vh;
    box-sizing: border-box;
    padding: 80rpx 40rpx 45rpx 40rpx;
    .login-footer {
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      font-size: 24rpx;
    }
    .wx-content {
      // margin-top: 550rpx;
      // position: absolute;
      // bottom: 170rpx;
      // left: 26rpx;
      // right: 26rpx;
    }
    .login-wx {
      // background: linear-gradient(135deg, #55baff 0%, #23e6d8 100%);
      width: 100%;
      line-height: 100rpx;
      height: 100rpx;
      color: #fff;
      font-size: 36rpx;
      border-radius: 18rpx;
      margin-bottom: 20rpx;
    }
    .login-wx::after {
      border: none !important;
    }
    .login-mobile {
      margin-bottom: 20rpx;
      font-size: 30rpx;
      color: #3bc5d2;
      font-weight: bold;
    }
    .diy-btn {
      color: #3bc5d2;
      font-size: 32rpx;
    }
    .u-model-btn-solid {
      border-right: solid 1rpx #ddd;
    }
  }
</style>
